import React, { useEffect, useState, memo } from 'react'
import 'antd/dist/antd.min.css'
import { DatePicker, Select, Tabs } from 'antd'
import './index.css'
import moment from 'moment'
import { Chart } from '@antv/g2'
import DataSet from '@antv/data-set'
import { ipList as presentIp } from '../../ipConfig'
import {
  preDay,
  nowDay,
  preWeek,
  nowMonth,
  preMonth,
  nowWeek,
  nowYear,
  preYear,
  getYearByNumber,
} from '../../utils'

const { TabPane } = Tabs
const { Option } = Select
const { RangePicker } = DatePicker

function HotelDynamic({ selectedTags, changeTimeDate }) {
  const [contentGraphIndex, setContentGraphIndex] = useState('入住率')
  const [timeIndex, setTimeIndex] = useState('昨日')
  const [time, setTime] = useState(preDay())
  const [indexOfSelectYear, setIndexOfSelectYear] = useState()
  const [dataOfSelectYears, setDataOfSelectYears] = useState(['今年'])
  const [colorOfTimeIndexYear, setColorOfTimeIndexYear] = useState('#000')
  const [dataOfOccupancyGraph, setDataOfOccupancyGraph] = useState(null)
  const [dataOfRentGraph, setDataOfRentGraph] = useState(null)
  const [hotellistId, setHotellistId] = useState()
  const [rangePickerValue, setRangePickerValue] = useState(false)
  const [rangePickerStartValue, setRangePickerStartValue] = useState('')
  const [rangePickerEndValue, setRangePickerEndValue] = useState('')

  useEffect(() => {
    let startYear = 2020
    let endYear = parseInt(moment(new Date()).format('YYYY'))
    let temp = []
    for (let i = endYear; i >= startYear; i--) {
      if (i === endYear) {
        temp.push('今年')
      } else if (i === endYear - 1) {
        temp.push('去年')
      } else {
        temp.push('' + i)
      }
    }
    setDataOfSelectYears(temp)
  }, [])

  useEffect(() => {
    const hotellistId = []
    selectedTags.map((item) => {
      hotellistId.push(item.hotelId)
      return item
    })

    setHotellistId(hotellistId)
  }, [selectedTags])

  useEffect(() => {
    if (hotellistId && hotellistId.length > 0) {
      let url = ''

      if (contentGraphIndex === '入住率') {
        url = `${presentIp.DEV_IP}/option_occupancy?hotellist=${hotellistId}&leftTime=${time[0]}&rightTime=${time[1]}`
      } else if (contentGraphIndex === '租金/收款') {
        url = `${presentIp.DEV_IP}/option_rental?hotellist=${hotellistId}&leftTime=${time[0]}&rightTime=${time[1]}`
      }

      fetch(url, {
        headers: {
          token: sessionStorage.getItem('token'),
        },
      })
        .then((response) => {
          return response.json()
        })
        .then((json) => {
          json = json.data
          if (contentGraphIndex === '入住率') {
            json.map(
              (value) => (value.livedRate = value.lived / value.nightAllnum)
            )
            json.sort(function (a, b) {
              return new Date(a.from) - new Date(b.from)
            })
            setDataOfOccupancyGraph(json)
          } else if (contentGraphIndex === '租金/收款') {
            json.sort(function (a, b) {
              return new Date(a.gmtCreate) - new Date(b.gmtCreate)
            })
            setDataOfRentGraph(json)
          }
        })
    }
  }, [time, contentGraphIndex, hotellistId])

  useEffect(() => {
    if (dataOfOccupancyGraph) {
      if (document.getElementById('content-graph-occupancy')) {
        document.getElementById('content-graph-occupancy').innerHTML = ''
        paintOccupancy(dataOfOccupancyGraph)
      }
    }
  }, [dataOfOccupancyGraph])

  useEffect(() => {
    if (dataOfRentGraph) {
      if (document.getElementById('content-graph-rent')) {
        document.getElementById('content-graph-rent').innerHTML = ''
        paintRent(dataOfRentGraph)
      }
    }
  }, [dataOfRentGraph])

  const paintOccupancy = (occupancyData) => {
    const chart = new Chart({
      container: 'content-graph-occupancy',
      autoFit: true,
      height: 440,
      padding: [25, 50, 25, 50],
    })

    chart.data(occupancyData)
    chart.scale('livedRate', {
      nice: true,
      alias: '入住率',
      range: [0, 0.9],
      formatter: (value) => {
        return (value * 100).toFixed(2) + '%'
      },
    })
    chart.scale('from', {
      range: [0.1, 0.9],
      tickCount: 10,
    })

    chart.axis('livedRate', {
      label: null,
    })

    chart.tooltip({
      showMarkers: false,
    })
    chart.interaction('active-region')

    const interval = chart
      .interval()
      .position('from*livedRate')
      .label('livedRate', (Value) => {
        return {
          content: (Value * 100).toFixed(2) + '%',
        }
      })
    chart.interaction('element-active')
    chart.render()
    if (timeIndex === '昨日') {
      for (let i = 0; i < 6; i++) {
        if (interval.elements[i])
          interval.elements[i].setState('inactive', true)
      }
    }
  }

  const paintRent = (rentData) => {
    const chart = new Chart({
      container: 'content-graph-rent',
      autoFit: true,
      height: 440,
      padding: [25, 50, 25, 50],
    })
    chart.scale('gmtCreate', {
      range: [0.05, 0.95],
    })
    chart.scale({
      range: {
        nice: true,
        sync: true,
      },
      value: {
        nice: true,
        sync: true,
      },
    })
    chart.axis('value', {
      label: {
        formatter: (text) => {
          return text.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
        },
      },
    })
    chart.tooltip({
      showCrosshairs: true,
      shared: true,
    })

    const ds = new DataSet()

    // view1
    const dv = ds
      .createView()
      .source(rentData)
      .transform({
        type: 'map',
        callback(row) {
          row.range = [row.payAmountCent, row.rental]
          return row
        },
      })
    const view1 = chart.createView({
      padding: [8, 8, 48, 64],
    })
    view1.data(dv.rows)
    view1.axis(false)
    view1.tooltip(false)
    view1.area().position('gmtCreate*range').color('#8d8d8d').style({
      fillOpacity: 0.1,
    })

    // view2
    const dv2 = ds
      .createView()
      .source(rentData)
      .transform({
        type: 'rename',
        map: {
          rental: '租金',
          payAmountCent: '收款',
        },
      })
      .transform({
        type: 'fold',
        fields: ['收款', '租金'],
        key: 'type',
        value: 'value',
        retains: ['gmtCreate'],
      })
    const view2 = chart.createView({
      padding: [8, 8, 48, 64],
    })
    view2.data(dv2.rows)
    view2.line().position('gmtCreate*value').color('type')
    view2.point().position('gmtCreate*value').color('type').shape('circle')

    chart.removeInteraction('legend-filter') // 关闭图例过滤交互

    chart.render()
  }

  const changeContentGraph = (key) => {
    setContentGraphIndex(key)
  }

  const changeTime = (index) => {
    let choice = ['昨日', '本周', '上周', '本月', '上月']
    setTimeIndex(index)
    switch (index) {
      case '今日':
        setTime(nowDay())
        changeTimeDate(nowDay())
        break
      case '昨日':
        setTime(preDay())
        changeTimeDate(preDay())
        break
      case '本周':
        setTime(nowWeek())
        changeTimeDate(nowWeek())
        break
      case '上周':
        setTime(preWeek())
        changeTimeDate(preWeek())
        break
      case '本月':
        setTime(nowMonth())
        changeTimeDate(nowMonth())
        break
      case '上月':
        setTime(preMonth())
        changeTimeDate(preMonth())
        break
      case '今年':
        setTime(nowYear())
        changeTimeDate(nowYear())
        break
      case '去年':
        setTime(preYear())
        changeTimeDate(preYear())
        break
      default:
        setTime(getYearByNumber(index))
        changeTimeDate(getYearByNumber(index))
    }

    // 清空日期选择框
    setRangePickerValue(false)
    setIndexOfSelectYear(index)

    // 设置年份的颜色
    setColorOfTimeIndexYear('#1890ff')
    for (let i = 0; i < choice.length; i++) {
      if (choice[i] === index) {
        setColorOfTimeIndexYear('#000')
        setIndexOfSelectYear('')
      }
    }
  }

  const changeStartEndDate = (dates, dateStrings) => {
    if (dates) {
      setRangePickerValue(true)
      setRangePickerStartValue(dateStrings[0])
      setRangePickerEndValue(dateStrings[1])
      setTime(dateStrings)
      setTimeIndex(dateStrings)
      changeTimeDate(dateStrings)
      setColorOfTimeIndexYear('#000')
      setIndexOfSelectYear('')
    } else {
      console.log('Clear')
    }
  }

  return (
    <>
      <div className="content-graph">
        <div className="content-graph-time">
          <ul className="content-graph-list">
            <li
              className="content-graph-item"
              onClick={() => changeTime('昨日')}>
              <div className={timeIndex === '昨日' ? 'item-blue' : ''}>
                昨日
              </div>
            </li>
            <li
              className="content-graph-item"
              onClick={() => changeTime('本周')}>
              <div className={timeIndex === '本周' ? 'item-blue' : ''}>
                本周
              </div>
            </li>
            <li
              className="content-graph-item"
              onClick={() => changeTime('上周')}>
              <div className={timeIndex === '上周' ? 'item-blue' : ''}>
                上周
              </div>
            </li>
            <li
              className="content-graph-item"
              onClick={() => changeTime('本月')}>
              <div className={timeIndex === '本月' ? 'item-blue' : ''}>
                本月
              </div>
            </li>
            <li
              className="content-graph-item"
              onClick={() => changeTime('上月')}>
              <div className={timeIndex === '上月' ? 'item-blue' : ''}>
                上月
              </div>
            </li>
            <li className="content-graph-item">
              <Select
                placeholder="今年"
                style={{
                  width: 80,
                  color: colorOfTimeIndexYear,
                }}
                bordered={false}
                onChange={changeTime}
                key={indexOfSelectYear ? indexOfSelectYear : 'null'}
                value={indexOfSelectYear ? indexOfSelectYear : null}>
                {dataOfSelectYears.map((item) => {
                  return (
                    <Option value={item} key={item}>
                      {item}
                    </Option>
                  )
                })}
              </Select>
            </li>
            <li className="content-graph-item">
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                value={
                  rangePickerValue === true
                    ? [
                        moment(new Date(rangePickerStartValue)),
                        moment(new Date(rangePickerEndValue)),
                      ]
                    : null
                }
                format={'YYYY-MM-DD'}
                onChange={changeStartEndDate}
                separator="~"
              />
            </li>
          </ul>
        </div>
        <Tabs defaultActiveKey="入住率" onChange={changeContentGraph}>
          <TabPane tab="入住率" key="入住率">
            <div
              style={{
                backgroundColor: 'rgba(0,0,0,.03)',
              }}>
              <div id="content-graph-occupancy"></div>
            </div>
          </TabPane>
          <TabPane tab="租金/收款" key="租金/收款">
            <div
              style={{
                backgroundColor: 'rgba(0,0,0,.03)',
              }}>
              <div id="content-graph-rent"> </div>
            </div>
          </TabPane>
        </Tabs>
      </div>
    </>
  )
}

export default memo(HotelDynamic)
